//
//  BDGuanzhuShopViewController.m
//  BadBoy
//
//  Created by wen on 2017/4/18.
//  Copyright © 2017年 com.8xiong. All rights reserved.
//

#import "BDGuanzhuShopViewController.h"
#import "BDShopTableViewCell.h"
#import "BDShopModel.h"
#import "BDShopInfoDeatilViewController.h"
#import "BDLocationServer.h"
#import "BDUserModel.h"

@interface BDGuanzhuShopViewController ()<UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *datasource;

@end

@implementation BDGuanzhuShopViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = @"关注商家";
    [self requestDatasource];
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:YES];
}

- (void)requestDatasource{
    BDLocationModel *locationModel = [BDLocationModel getLocationInfo];
    NSString *url = [NSString stringWithFormat:@"%@shops?page=%@&size=%@&order=1&user_lng=%f&user_lat=%f&fav=1", KBDBaseURL, self.startPage, self.pageSize, locationModel.longitude, locationModel.latitude];
    NSString *headValid = [BDUserModel getHeaderValidation];
    RACSignal *signal = [[BDNetworkingServer yy_GET:url parameters:nil validation:headValid automaticProcessingError:YES] execute:nil];
    [signal subscribeNext:^(id  _Nullable x) {
        self.startPage = x[@"next_page"];
        self.isEnd = [x[@"is_end"] boolValue];
        [self.datasource addObjectsFromArray:[BDShopModel mj_objectArrayWithKeyValuesArray:x[@"list"]]];
        
        [self.tableView.mj_footer endRefreshing];
        [self.tableView.mj_header endRefreshing];
        [self.tableView reloadData];
        
        self.tableView.mj_footer = [MJRefreshBackFooter footerWithRefreshingBlock:^{
            [self requestDatasource];
        }];
        [self setTableiewFooterViewStateFor:self.tableView datasourceCount:self.datasource.count guanzhuShangjia:nil];
    }];
    [signal subscribeError:^(NSError * _Nullable error) {
        [self showErrorViewWithTapBlock:^{
            
        }];
    }];
    
    //    self.datasource = nil;
    //    self.isEnd = YES;
    //    [self setTableiewFooterViewStateFor:self.tableView datasourceCount:0];
}

#pragma mark -----------------------tableView代理-------------------------------
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    return YES;
}

- (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath{
    return @"删除";
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (editingStyle ==UITableViewCellEditingStyleDelete) {
        BDShopModel *shopModel = self.datasource[indexPath.row];
        NSString *url = [NSString stringWithFormat:@"%@shop/%@/fav", KBDBaseURL, @(shopModel.shop_id)];
        NSString *headValid = [BDUserModel getHeaderValidation];
        [MBManager showLoadingAlert:@"请稍后" clickHidden:NO clickBlock:nil];
        RACSignal *signal = [[BDNetworkingServer yy_POST:url parameters:nil validation:headValid automaticProcessingError:YES] execute:nil];
        [signal subscribeNext:^(id  _Nullable x) {
            [MBManager hideAlert];
            [self.datasource removeObject:shopModel];
            [self.tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
            if (self.datasource.count == 0) {
                [self setTableiewFooterViewStateFor:self.tableView datasourceCount:0];
            }
        }];
        
        [signal subscribeError:^(NSError * _Nullable error) {
//            [MBManager hideAlert];
            [MBManager showBriefAlert:@"删除失败" clickHidden:NO clickBlock:nil];
        }];
        
        
    }
    else if (editingStyle ==UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view.
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.datasource.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *cellID = @"cellID";
    BDShopTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
    if (!cell) {
        cell = [[BDShopTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    if (self.datasource.count != 0) {
        [cell configeWithModel:self.datasource[indexPath.row] index:-1];
    }
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    BDShopInfoDeatilViewController *bussinessVC = [[BDShopInfoDeatilViewController alloc]init];
    bussinessVC.hidesBottomBarWhenPushed = YES;
    //商家id
    BDShopModel *shopModel = self.datasource[indexPath.row];
    bussinessVC.shopID = [NSString stringWithFormat:@"%ld", shopModel.shop_id];
    bussinessVC.title = shopModel.title;
    __weak BDGuanzhuShopViewController *weakSelf = self;
    bussinessVC.favBlock = ^{
        [weakSelf.datasource removeObject:shopModel];
        [weakSelf.tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
        if (weakSelf.datasource.count == 0) {
            [weakSelf setTableiewFooterViewStateFor:weakSelf.tableView datasourceCount:0];
        }
    };
    [self.navigationController pushViewController:bussinessVC animated:YES];
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 90;
}

- (UITableView *)tableView{
    if (!_tableView) {
        self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, kBDTopHeight, kBDScreenWidth, kBDScreenHeight - kBDTopHeight) style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.tableFooterView = [[UIView alloc]initWithFrame:CGRectZero];
        _tableView.backgroundColor = [UIColor clearColor];
        //        _tableView.layer.shadowOffset = CGSizeMake(0, 0);
        //        _tableView.layer.shadowColor = [UIColor blackColor].CGColor;
        //        _tableView.layer.shadowOpacity = 0.5;
        //        _tableView.layer.shadowRadius = 5;
        //        _tableView.clipsToBounds = NO;
        
        _tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
            self.startPage = @"1";
            [self.datasource removeAllObjects];
            [self requestDatasource];
        }];
        [self.view addSubview:_tableView];
    }
    return _tableView;
}

- (NSMutableArray *)datasource{
    if (!_datasource) {
        self.datasource = [NSMutableArray array];
    }
    return _datasource;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end

